
use std::io::stdout;
use std::time::Duration;
use anyhow::Result;

use crossterm::{event, execute, terminal::{enable_raw_mode, disable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}};
use crossterm::event::{DisableMouseCapture, Event, KeyCode};
use ratatui::{prelude::*, widgets::{Block, Borders}} ;
fn main() -> Result<()> {
    // 1. 进入备用屏 + raw mode 
    enable_raw_mode()?; 
    let mut stdout = stdout();
    execute!(stdout, EnterAlternateScreen)?; 
    
    // 2. 初始化ratatui
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;
    
    // 3. 主循环 
    loop {
        terminal.draw(|f| {
            let size = f.size() ;
            let block = Block::default().title("Hello~ press q to quit").borders(Borders::ALL);
            f.render_widget(block, size);
        })?;
        if event::poll(Duration::from_millis(200))? {
            if let Event::Key(key) = event::read()? {
                if matches!(key.code , KeyCode::Char('q') |  KeyCode::Esc) {
                    break ;
                }
            }
        }
    }
   
    // 4. 离开备用屏  关闭raw mode
    execute!(terminal.backend_mut(), LeaveAlternateScreen , DisableMouseCapture)?;
    disable_raw_mode()?;
    Ok(())
}